<template>
    <div class="wrap">
        <!--信息头-->
        <span>发布商品</span>
        <el-divider></el-divider>
        <!-- 要带上用户/企业id给 -->
        <div class="banner">
            <el-card class="card_class">
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" label-position="top">
                    <el-tabs v-model="activeIndex" :tab-position="'left'" :before-leave="beforeLeave">
                        <el-tab-pane label="基本信息" name="0">
                            <el-form-item label="商品名称" prop="goods_sku_name">
                                <el-input v-model="ruleForm.goods_sku_name" clearable></el-input>
                            </el-form-item>
                            <el-form-item label="商品分类" prop="goods_type_id">
                                <el-select v-model="ruleForm.goods_type_id" placeholder="商品大类" @change="onTypeChange">
                                    <el-option label="铝土矿" value="1"></el-option>
                                    <el-option label="氧化铝" value="2"></el-option>
                                    <el-option label="电解铝" value="3"></el-option>
                                    <el-option label="成品铝" value="4"></el-option>
                                </el-select>
                            </el-form-item>
                            <!-- <el-form-item>
                                <el-option v-for="(spu,index) in spuList" :key="index" :label="index" :value="spu"></el-option>                        
                            </el-form-item> -->
                            <el-form-item>
                                <el-select v-model="ruleForm.goods_spu_id" placeholder="商品种类" prop="goods_spu_id" @change="onSpuChange">
                                    <el-option v-for="spu in spuList" :key="spu.goods_spu_id" :label="spu.goods_spu_name" :value="spu.goods_spu_id"></el-option>                        
                                </el-select>
                            </el-form-item>
                            <el-form-item label="商品详情" prop="goods_sku_desc">
                                <el-input v-model="ruleForm.goods_sku_desc" clearable></el-input>
                            </el-form-item>
                            <!-- 不允许发布绑定企业之外的其他企业的商品 -->
                            <!-- <el-form-item label="企业名字" prop="fname">
                                <el-input v-model="ruleForm.name"></el-input>
                            </el-form-item> -->
 
                            <el-form-item label="预期价格(元/千克)" prop="goods_sku_price">
                                <el-input v-model="ruleForm.goods_sku_price" type="number" @focus="inputFocus" @keydown.native="inputLimit"></el-input>
                            </el-form-item>
                            <el-form-item label="商品图像">
                                <el-upload
                                        class="avatar-uploader"
                                        action="http://ip:port/file/upload"
                                        :show-file-list="false"
                                        :on-success="handleAvatarSuccess"
                                        :before-upload="beforeAvatarUpload">
                                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                </el-upload>
                            </el-form-item>
                        </el-tab-pane>
                        <el-tab-pane label="商品参数" name="1">
                            <!-- 需要读取分类数据(spu-id) -->
                            <div v-if="this.ruleForm.goods_spu_id!==''">
                                <el-form-item v-for="(spec,index) in goods_spec" :key="index" :label="spec">
                                    <el-input v-model="ruleForm.cols[index]"></el-input>
                                </el-form-item>
                            </div>
                            <el-form-item label="参数" v-if="this.ruleForm.goods_spu_id===''" >
                                <el-input placeholder="无可用参数" :disabled="true"></el-input>
                            </el-form-item>
                        </el-tab-pane>
                        <el-tab-pane label="联系方式" name="2">
                            <el-form-item label="联系电话" prop="firm_phone">
                                <el-input v-model="ruleForm.firm_phone" type="number" @focus="inputFocus" @keydown.native="inputLimit"></el-input>
                            </el-form-item>
                            <el-form-item label="联系邮箱" prop="firm_mail">
                                <el-input v-model="ruleForm.firm_mail"></el-input>
                            </el-form-item>
                            <el-form-item align="right">
                                <el-button type="primary" @click="add">发布</el-button>
                                <el-button>取消</el-button>
                            </el-form-item>
                        </el-tab-pane>
                    </el-tabs>

                </el-form>
            </el-card>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            imageUrl: '',
            ruleForm: {
                goods_sku_name: '',
                goods_sku_id: '',
                goods_spu_id:'',
                // 后端自动生成日期，这里不用填
                goods_type_id: '',
                goods_sku_desc: '',   
                cols:["1","2","3"],
                goods_sku_spec:"",
            },
            activeIndex:"0",
            selected:false,
            goodsSpecList: {"1":["含铝量","铝硅比"],
                            "2":["含铝量","铝硅比"],
                            "3":["长","宽","高"],
                            "4":["长","宽","高"],
                            "5":["长","宽","高"],
                            "6":["长","宽","高"],
                            "7":["平均粒度"],
                            "8":["长","宽","高"],
                            "9":["长","宽","高"],
            },
            goods_spec:["参数1","参数2","参数3"],//属性名
            
            
            rules: {
                goods_sku_name: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' },
                    { max: 10, message: '长度在10个字符以下', trigger: 'blur' }
                ],
                goods_sku_id: [
                    { required: true, message: '请选择商品大类', trigger: 'change' }
                ],
                firm_email:[
                    {
                        required: false,
                        pattern:/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
                        message: '请输入正确的邮箱',
                        trigger: 'blur'
                   }
                ],
                goods_spu_id: [
                    { required: true, message: '请选择商品种类', trigger: 'change' }
                ],
            },
            sampleData:[],
            spuList:[],
            testList:{"1":[{"goods_spu_id":1,"goods_spu_name":"古风化壳矿土",},{"goods_spu_id":2,"goods_spu_name":"红土"}],
                      "2":[{"goods_spu_id":7,"goods_spu_name":"α型氧化铝",}],
                      "3":[{"goods_spu_id":4,"goods_spu_name":"AC4D",},{"goods_spu_id":5,"goods_spu_name":"AC5A"},{"goods_spu_id":6,"goods_spu_name":"A308"}],
                      "4":[{"goods_spu_id":8,"goods_spu_name":"铝条",},{"goods_spu_id":9,"goods_spu_name":"铝板",}]
            },
            postFormUrl:"http://localhost:port/goodsSku/create",
            getUrl2:"http://localhost:8009/goodsSpu/get-spu/",
            getUrl:"http://localhost:8009/goodsSpu/get-spec-name/",
        };
    },
    methods: {
        onTypeChange()
        {
            console.log(this.ruleForm.goods_type_id)

            // this.spuList = this.getSpuList()
            this.ruleForm.goods_spu_id = ''
            this.spuList = this.testList[this.ruleForm.goods_type_id]
            
            console.log(this.spuList)

        },
        onSpuChange()
        {
            // this.goods_spec = this.getSpecName()
            this.goods_spec = this.goodsSpecList[this.ruleForm.goods_spu_id]
            console.log(this.ruleForm.goods_spu_id)
            // console.log(this.goods_spec)
        },
        inputLimit(e)
        {
            let key = e.key
            if(key === 'e' || key === '.')
            {
                this.$message.error("只能输入数字！")
                e.returnValue = false
                return false
            }
            return true
        },
        async getSpuList()
        {
            await this.$http.get(this.getUrl+this.ruleForm.goods_type_id).then(function(result){
                this.spuList = result.data  //列表
            })
        },
        async getSpecName()
        {
            
            this.goods_spec = []
            this.ruleForm.cols = []
            await this.$http.get(this.getUrl2 + this.ruleForm.goods_spu_id).then((result)=>{
                //如果这里仍是字符串则需要转为json
                //否则如果是json格式直接将key都放[](goods_spec)里面去
                for(var i in result.data)
                {
                    this.goods_spec.push(i)
                    this.cols.push(i)
                }
            })
        },
        beforeLeave(activeName,oldActiveName)
        {
            if(oldActiveName === "0" && this.ruleForm.goods_spu_id === "")
            {
                this.$message.error("需要选定商品种类")
                return false
            }
            return true
        },
        add()
        {
            // this.ruleForm.validate((valid)=>{
            //     if(!valid)
            //     {
            //         return this.$message.error("请按要求填写表单")
            //     }
            // });
            //将填写的表格重写成String->不用，后端接收到了再改
            /*
                {""}
            */
        //    this.submitForm("ruleForm")
        //    this.ruleForm.packedSpec = {}
        //    for(var name in this.goods_spec)
        //    {
        //        this.ruleForm.packedSpec[name] = this.ruleForm[name]
        //    }
        //    console.log(this.ruleForm.packedSpec)
           this.$refs.ruleForm.validate((valid)=>{
                if (valid) {
                    alert('submit!')
                    // this.$http.post(postFormUrl,cre_para).then(function(res){console.log(res)})
                    console.log(this.ruleForm)

                } else {
                    console.log('error submit!!');
                    return false;
                }
           })
           console.log(this.ruleForm.goods_sku_spec)
           this.ruleForm.goods_sku_spec = JSON.stringify(this.ruleForm.cols)
           console.log(this.ruleForm.goods_sku_spec)
           console.log(this.ruleForm)
        // this.submitForm()
        },
        async submitForm() {
            var cre_para = {}
            cre_para = JSON.stringify(this.ruleForm)
            await this.$http.post(this.postFormUrl,cre_para).then((result)=>{
                if(result.success == true)
                {
                    alert("提交成功！")
                }
                else
                {
                    alert("提交失败，请重试！")
                }
            })
        },
        resetForm() {
            this.ruleForm.resetFields();
        },
        handleAvatarSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        }
    }
}
</script>

<style lang="less" scoped>
    .wrap{
        .banner{
            width: 980px;
            height: 100%;
            .card_class{
                width: 800px;
                height: 100%;
                margin: 0 auto;
            }
        }
    }
    // 上传图片样式
    .avatar-uploader{
        width: 178px;
        height: 178px;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>
